package com.example.java_chatroom.controller;

import com.example.java_chatroom.model.Result;
import com.example.java_chatroom.model.User;
import com.example.java_chatroom.server.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/registry")
    public Result<User> registry(String userName,String password) {
        log.info("userName:" + userName + " password:" + password);
        if (!StringUtils.hasLength(userName) || !StringUtils.hasLength(password)) {
            return Result.fail(404,new User(),"账号或者密码为空");
        }
        User user = new User();
        user.setUserName(userName);
        user.setPassword(password);
        try {
            int ret = userService.registry(user);
            if (ret <= 0) {
                return Result.fail(500,user,"注册失败，请联系管理员");
            }else {
                return Result.success(user);
            }
        }catch (DataIntegrityViolationException e) {
            e.printStackTrace();
            return Result.fail(404,user,"该用户已存在！");
        }
    }
}
